<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/layui/css/layui.css"  media="all">
    <!-- 注意：如果你直接复制所有代码到本地，上述css路径需要改成你本地的 -->
</head>
<body>

<table class="layui-hide" id="test" lay-filter="test"></table>

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="getCheckData">批量删除</button>
        <button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>
        <button class="layui-btn layui-btn-sm" lay-event="isAll">验证是否全选</button>
        <button class="layui-btn layui-btn-sm" lay-event="excel">导出Excel</button>
    </div>
</script>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>


<script src="/layui/layui.js" charset="utf-8"></script>
<!-- 注意：如果你直接复制所有代码到本地，上述 JS 路径需要改成你本地的 -->
<!-- 引入jquery.js -->
<!--<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js"></script>-->
<script src="/jquary/jquery-1.8.3.js"></script>

<script>
    layui.use('table', function(){
        var table = layui.table;

        table.render({
            elem: '#test'
            ,url:'/goods/findByPage'
            ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            ,defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
                title: '提示'
                ,layEvent: 'LAYTABLE_TIPS'
                ,icon: 'layui-icon-tips'
            }]
            ,title: '用户数据表'
            ,page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                limit:2,
                limits:[1,2,3],
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                ,groups: 1 //只显示 1 个连续页码
                ,first: false //显示首页
                ,last: false //显示尾页
            }
            ,cols: [[
                {type: 'checkbox', fixed: 'left'}
                ,{field:'goodId', title:'商品编号', width:80, fixed: 'left', unresize: true, sort: true}
                ,{field:'goodName', title:'商品名称', width:80, edit: 'text',sort: true}
                ,{field:'categoryId', title:'所属分类', width:120, edit: 'text'}
                ,{field:'salePrice', title:'价格', width:120,sort: true}
                ,{field:'remainingCount', title:'剩余数量',width:120,sort: true}
                ,{fixed: 'right', title:'操作', toolbar: '#barDemo', width:150}
            ]]
            //,page: true
        });

        //头工具栏事件
        table.on('toolbar(test)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'getCheckData':
                    var data = checkStatus.data;

                    // layer.alert(JSON.stringify(data));

                    //-------------批量删除操作-----------
                    //声明一个变量，用来存储id
                    var ids = '';
                    //遍历data获取id &id=1&id=2...
                    for (var i = 0; i < data.length; i++) {
                        ids += "&goodIds=" + data[i].goodId;
                    }
                    layer.alert(ids);

                    //使用ajax进行提交到后台进行处理
                    $.post("goods/deleteAll", ids,
                        function(data){
                            layer.alert("function");
                            if("success" == data){
                                // layer.alert("success");
                                window.location.href="http://localhost:8080/index.html";
                            }
                        });
                    /*$.ajax({
                        type:"post",
                        url:"goods/deleteAll",
                        data:{ids},
                        async: true,
                        success:function (result) {
                            if ("success" == result) {
                                window.location.href="http://localhost:8080/index.html";
                            }
                        },
                        dataType:"json"
                    });*/
                    //-----------------------------------
                    break;
                case 'getCheckLength':
                    var data = checkStatus.data;
                    layer.msg('选中了：'+ data.length + ' 个');
                    break;
                case 'isAll':
                    layer.msg(checkStatus.isAll ? '全选': '未全选');
                    break;

                //自定义头工具栏右侧图标 - 提示
                case 'LAYTABLE_TIPS':
                    layer.alert('这是工具栏右侧自定义的一个图标按钮');
                    break;
                case 'excel':
                    var data = checkStatus.data;

                    var ids = '';

                    for (var i = 0; i < data.length; i++) {
                        ids += "&ids=" + data[i].id;
                    }

                    $.get("user/excel", ids,
                        function(data){
                            alert(data);
                        });

                    break;
            };
        });

        //监听行工具事件
        table.on('tool(test)', function(obj){
            var data = obj.data;
            //console.log(obj)
            if(obj.event === 'del'){
                layer.confirm('真的删除行么', function(index){
                    obj.del();
                    layer.close(index);

                    //从数据库中删除
                    $.ajax({
                        type: "POST",
                        url: "goods/deleteGoodsById",
                        data: "id="+data.goodId,
                        success: function(msg){
                            //location.reload();//重新加载当前页面
                            table.reload("test",{});
                        }
                    });

                });
            } else if(obj.event === 'edit'){
                // layer.alert('编辑行：<br>'+ JSON.stringify(data))
                //首先调用的是查询单个的方法
                queryOne(data);
            }
        });
    });
</script>

<script type="text/html" id="img">
    <div><img src="{{d.userImage}}" width="40" height="40" alt="图片"></div>
</script>

<script>
    function queryOne(data) {
        layer.open({
            title: ['修改用户'],
            type: 1,
            content: $("#updateUser").html(), //我要修改的页面
            area: ['600px', '600px'],
            btn: ['提交','取消'],
            //弹出窗口以后的回调函数
            success: function () {

                $("#goodId").val(data.goodId);
                $("#goodName").val(data.goodName);

                //下拉菜单
                /*if("1" == data.categoryId){
                    $("#categoryId").append('<option value="1" selected>衣服</option><option value="2">物品</option>')
                }else {
                    $("#categoryId").append('<option value="1">衣服</option><option value="2" selected>物品</option>')
                }*/
                $.ajax({
                    type:"get",
                    url:"goods/findGoodsCategory",
                    success:function (userlist) {
                        var element = document.getElementById("categoryId");
                        if (userlist != null) {
                            // layer.alert(userlist);
                            // layer.alert("userlist");
                            for (var i = 0; i < userlist.length; i++) {
                                // $("#categoryId").option.add(new Option(userlist[i].categoryId, userlist[i].categoryName));
                                $("#categoryId").append("<option value="+userlist[i].categoryId+">" + userlist[i].categoryName + "</option>");
                            }
                        }
                        layui.form.render();//渲染页面
                    },
                    error:function () {
                        J.alert('Error');
                    }
                })

                $("#salePrice").val(data.salePrice);
                $("#remainingCount").val(data.remainingCount);

                //渲染页面
                layui.form.render();
            },
            //提交调用该函数
            yes: function () {
                $.ajax({
                    type:"post",
                    url:"goods/updateGoods",
                    data:$("#updateUserForm").serialize(),
                    success:function (result) {
                        location.reload();//重新加载当前页面
                    },
                });
            },
            //取消
            btn2: function () {
                alert("已取消");
            }
        });
    }
</script>

<script type="text/html" id="updateUser">

    <form id="updateUserForm" class="layui-form">
        <!--页面上不显示id，但是需要作为隐藏域传递-->
        <input type="hidden" id="goodId" name="goodId">

        <div class="layui-form-item">
            <label class="layui-form-label">商品名称</label>
            <div class="layui-input-block">
                <input id="goodName" type="text" name="goodName" lay-verify="title" autocomplete="on" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">所属分类</label>
            <div class="layui-input-block">
                <select name="categoryId" id="categoryId" >

                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">价格</label>
            <div class="layui-input-block">
                <input id="salePrice" type="text" name="salePrice" lay-verify="title" autocomplete="off" class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">剩余数量</label>
            <div class="layui-input-block">
                <input id="remainingCount" type="text" name="remainingCount" lay-verify="title" autocomplete="off" class="layui-input">
            </div>
        </div>


    </form>

</script>

<script>
    layui.use(["laydate","form"],function(){
        var laydate = layui.laydate;
        //执行一个laydate实例
        laydate.render({
            elem: '#userBirthdate', //指定元素
            format:'yyyy-MM-dd',
        });
    });
</script>

<script>


</script>

</body>
</html>